﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RBAC_Class.Read.API.Application.Command.Permissions;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;
using System;
using System.Threading.Tasks;
using NLog;

namespace RBAC_Class.API.Controllers
{
    /// <summary>
    /// 权限控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PermissionController : ControllerBase
    {
        // 注入中介者
        private readonly IMediator mediator;
        private readonly ILogger<PermissionController> logger;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">注入中介者</param>
        public PermissionController(IMediator mediator, ILogger<PermissionController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }
        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <param name="cmd">命令</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<List<Permission>>>> PermissionQuery
            ([FromQuery] PermissionQueryCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "权限查询失败 - 参数: PageIndex={PageIndex}, PageSize={PageSize}", 
                    cmd.PageIndex, cmd.PageSize);
                throw;
            }
        }
        /// <summary>
        /// 获取权限复选框
        /// </summary>
        [HttpGet]
        public async Task<APIResult<List<Permission>>> GetPermission()
        {
            try
            {
                GetPermissionCommand cmd = new GetPermissionCommand();
                return await mediator.Send(cmd);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取权限失败");
                throw;
            }
        }
        
    }
}
